package net.cyue.homework.student.management.servlet.user;


import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import net.cyue.homework.student.management.dto.UserLoginDTO;
import net.cyue.homework.student.management.http.HTTPServlet;
import net.cyue.homework.student.management.http.annotation.PostMethod;
import net.cyue.homework.student.management.util.CodeUtil;
import net.cyue.homework.student.management.util.DB;
import net.cyue.homework.student.management.util.ResponseUtil;
import net.cyue.nest.nestjava.common.annotation.Body;
import net.cyue.nest.nestjava.common.annotation.Request;
import net.cyue.nest.nestjava.common.annotation.Response;
import net.cyue.nest.nestjava.common.enums.HTTPStatus;
import net.cyue.nest.nestjava.common.interfaces.http.IHTTPRequest;
import net.cyue.nest.nestjava.common.interfaces.http.IHTTPResponse;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "UserLoginServlet", value = "/action/user/login")
public class UserLoginServlet extends HTTPServlet {

    @PostMethod
    public void doPost(
        @Request IHTTPRequest request,
        @Response IHTTPResponse response,
        @Valid @Body UserLoginDTO dto
    ) {
        if (
            !CodeUtil.verifyCode(request, dto.getCode())
        ) {
            response.status(HTTPStatus.BAD_REQUEST);
            ResponseUtil.showMessage(response, "验证码错误");
            return;
        }

        String sql = DB.generateSQL(
            "SELECT * FROM user WHERE username = ? AND password = ?",
            List.of(
                dto.getUsername(),
                dto.getPassword()
            )
        );
        try {
            ResultSet resultSet = DB.POOL.query(sql);
            if (!resultSet.next()) {
                response.status(HTTPStatus.BAD_REQUEST);
                ResponseUtil.showMessage(response, "用户名或密码错误");
                return;
            }
            int userID = resultSet.getInt("id");
            HttpSession session = request.getSession();
            session.setAttribute("userID", userID);
            session.setAttribute("username", dto.getUsername());
            resultSet.close();
            ResponseUtil.waitBackHome(response, 2000, "登录成功");
        } catch (SQLException e) {
            e.printStackTrace();
            response.status(HTTPStatus.INTERNAL_SERVER_ERROR);
            ResponseUtil.waitBack(response, 1500, "内部错误");
        }

    }

}


